const express = require("express");
const router = express.Router();
const multer = require("multer");
const https = require("https");
const qs = require("querystring");
const sharp = require("sharp");
const path = require("path");

const {
  getData,
  getHotData,
  getDetail,
  getListData,
  getMapData,
  getUserFavoriteData,
  updateUserInfo,
  addFeedback,
  getFeedback,
  addComment,
  getUserComment,
  getCollectData,
  addFavorite,
  removeFavorite,
  getHasFav,
  recommentData,
  userLogin,
  getUserInfo,
  getCommentData,
  addRecoverComment,
} = require("../../router_handler/api/data");

// 上传图片

/**
 * 文件上传的处理函数
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    if (req.headers.type) {
      cb(null, `./public/uploads/${req.headers.type}/`);
    } else {
      cb(null, `./public/uploads/`);
    }
  },
  filename: (req, file, cb) => {
    cb(null, `${Date.now()}`);
  },
});

const upload = multer({ storage: storage });

// 文件上传

// 文件上传处理函数
router.post("/upload", upload.array("file"), async (req, res) => {
  try {
    // 处理上传的文件
    const files = req.files;
    const convertedFiles = [];

    // 遍历上传的文件并使用 sharp 转换为 webp 格式
    for (const file of files) {
      // 读取上传的文件流
      const originalFilePath = file.path;
      const webpFilePath = path.join(
        path.dirname(originalFilePath),
        file.filename + ".webp"
      );
      const pipeline = sharp(originalFilePath)
        .webp()
        .toFormat("webp", { quality: 100 }) // 无损压缩
        .toFile(webpFilePath);

      // 等待转换完成
      await pipeline;
      convertedFiles.push(webpFilePath);
    }

    // 构建响应数据，包含转换后的图片路径
    const imagePaths = convertedFiles.map((file) => {
      return (
        `${req.protocol}://${req.headers.host}${path.join(
          "/" + path.dirname(file)
        )}/` + path.basename(file)
      );
    });
    // 发送响应
    res.send({ code: 200, data: imagePaths });
  } catch (error) {
    // 错误处理
    console.error("Error processing files:", error);
    res.status(500).send({ code: 500, message: "Internal Server Error" });
  }
});
/**
 * @api {get} /api/getIndexData 获取首页数据
 * @apiName getIndexData
 * @apiGroup api
 * @apiVersion 1.0.0
 *
 * @apiSuccess {Number} code 状态码
 * @apiSuccess {Boolean} ok 状态
 * @apiSuccess {Object} data 数据
 *
 * @apiError {Number} code 状态码
 * @apiError {Boolean} ok 状态
 * @apiError {String} message 错误描述
 */
router.get("/getIndexData", async (req, res) => {
  let { location, distance } = req.query;
  location = JSON.parse(location);
  const data = await getData(location, +distance);
  res.send(data);
});
/**
 * @api {get} /api/getHotData 获取热门数据
 * @apiName getHotData
 * @apiGroup api
 * @apiVersion 1.0.0
 *
 * @apiSuccess {Number} code 状态码
 * @apiSuccess {Boolean} ok 状态
 * @apiSuccess {Object} data 数据
 *
 * @apiParam {Number} limit 获取条数
 * @apiParam {Number} offset 偏移
 *
 * @apiError {Number} code 状态码
 * @apiError {Boolean} ok 状态
 * @apiError {String} message 错误描述
 */
router.get("/getHotData", async (req, res) => {
  const { page, size } = req.query;
  const limit = size;
  const offset = (page - 1) * limit;
  const data = await getHotData(limit, offset);
  res.send(data);
});
/**
 * @api {get} /getDetail/:type/:id 获取详情
 * @apiName getDetail
 * @apiGroup Detail
 *
 * @apiParam {String} type 类型
 * @apiParam {String} id id
 *
 * @apiSuccess {Object} data 数据
 *
 * @apiError {Number} code 状态码
 * @apiError {Boolean} ok 状态
 */
router.get("/getDetail", async (req, res) => {
  const { type, id } = req.query;

  let data = await getDetail(type, id);
  res.send(data);
});
/**
 * @api {get} /getListData 获取列表数据
 */
router.get("/getListData", async (req, res) => {
  let { type, location, limit, page } = req.query;
  let offset = (page - 1) * limit;
  location = location ? location : "";
  let data = await getListData(type, location, limit, offset);
  res.send(data);
});
/**
 * @api {get} /getCommentData 获取评论数据
 *
 */
router.get("/getCommentData", async (req, res) => {
  let { limit, page, userId, type, typeId } = req.query;
  let offset = (page - 1) * limit;
  // let data = await getCommentData(limit, offset, userId, type, typeId);

  let data = await getCommentData(+limit, offset, userId, type, typeId);
  res.send(data);
});
/**
 * @api {get} /getMapData 获取地图数据
 *
 */
router.get("/getMapData", async (req, res) => {
  let { page, limit, location, type, distance } = req.query;
  let offset = (page - 1) * limit;
  location = { longitude: 112.495348, latitude: 23.06205 };
  let data = await getMapData(location, type, distance);
  res.send(data);
});

/**
 * @api {get} /getFavoriteData 获取收藏数据
 *
 */
router.get("/getFavoriteData", async (req, res) => {
  let { limit, page, userId, type } = JSON.parse(req.query.params);
  let offset = (page - 1) * limit || 0;

  let data = await getUserFavoriteData(limit, offset, userId, type);
  res.send(data);
});
/**
 * @api {get} /getHasFav 获取收藏状态
 *
 */
router.get("/getHasFav", async (req, res) => {
  let { userId, type, typeId } = req.query;
  let data = await getHasFav(userId, type, typeId);
  res.send(data);
});
/**
 * @api {post} /addFavorite 添加收藏
 *
 */
router.post("/addFavorite", async (req, res) => {
  let { userId, type, typeId } = req.body;
  let data = await addFavorite(userId, type, typeId);
  res.send(data);
});
/**
 * @api {post} /removeFavorite 移除收藏
 *
 */
router.post("/removeFavorite", async (req, res) => {
  let { userId, type, typeId } = req.body;
  let data = await removeFavorite(userId, type, typeId);
  res.send(data);
});

/**
 * @api {post} /login 登录
 *
 */
router.post("/login", (req, res) => {
  const { WECHAT_APPID, WECHAT_SECRET } = process.env;
  let session_key = "";
  let openid = "";

  const query = {
    appid: WECHAT_APPID,
    secret: WECHAT_SECRET,
    js_code: req.body.code,
    grant_type: "authorization_code",
  };
  const content = qs.stringify(query);
  const options = {
    hostname: "api.weixin.qq.com",
    port: 443, // 微信的 API 通常使用 443 端口
    path: "/sns/jscode2session?" + content,
    method: "GET",
    headers: {
      "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
      "Content-Length": Buffer.byteLength(content),
      Connection: "keep-alive",
    },
  };

  const getOpenid = https.request(options, (response) => {
    let parsData = "";
    response.on("data", (chunk) => {
      parsData = JSON.parse(chunk);
    });
    response.on("end", async () => {
      try {
        session_key = parsData.session_key;
        openid = parsData.openid;

        let data = await userLogin(req.body, openid, session_key);
        res.send(data);
      } catch (error) {
        res.send({ code: 500, message: error });
      }
    });
  });

  getOpenid.on("error", (error) => {
    console.error("problem with request:", error.message);
    res.status(500).send({ code: 500, message: "Login failed" });
  });

  getOpenid.write(content);
  getOpenid.end();
});
/**
 * @api {get} /getUserInfo 获取用户信息
 *
 */
router.get("/getUserInfo", async (req, res) => {
  let { userId } = req.query;

  let data = await getUserInfo(userId);

  res.send(data);
});
/**
 * @api {put} /updateUserInfo 更新用户信息
 *
 */
router.post("/updateUserInfo", async (req, res) => {
  let { userId, nickname, phone, avatar, gender } = req.body;
  let data = await updateUserInfo(userId, nickname, phone, avatar, gender);
  res.send(data);
});
/**
 * @api {get} /getFeedback 获取反馈
 *
 */
router.get("/getFeedback", async (req, res) => {
  let { size, page, userId } = JSON.parse(req.query.params);
  let offset = (page - 1) * size;
  let data = await getFeedback(size, offset, userId);
  res.send(data);
});

/**
 * @api {post} /addFeedback 添加反馈
 *
 */
router.post("/addFeedback", async (req, res) => {
  let { content, people, contact, image, userId } = req.body.params;
  userId = "123";

  let data = await addFeedback(
    content,
    people,
    contact,
    JSON.stringify(image),
    userId
  );
  res.send(data);
});
/**
 * @api {get} /getUserComment 获取用户评论
 *
 */
router.get("/getUserComment", async (req, res) => {
  let { userId, page, limit } = JSON.parse(req.query.params);
  let offset = (page - 1) * limit;
  let data = await getUserComment(userId, offset, limit);
  res.send(data);
});

/**
 * @api {post} /addComment 添加评论
 *
 */
router.post("/addComment", async (req, res) => {
  let { userId, comment, rate, type, id, image } = req.body.params;

  let data = await addComment(
    userId,
    comment,
    rate,
    type,
    id,
    JSON.stringify(image)
  );
  res.send(data);
});
/**
 * @api {post} /addRecoverComment 添加回复评论
 *
 */
router.post("/addRecoverComment", async (req, res) => {
  const { content, userId, parentId } = req.body;
  let data = await addRecoverComment(content, userId, parentId);
  res.send(data);
});

/**
 * @api {post} /recommendData 推荐数据
 *
 */
router.post("/recommendData", async (req, res) => {
  let data = await recommentData(req.body);
  res.send(data);
});
// 导出路由
module.exports = router;
